const cdkService = require('../service/cdk.service')
const userService = require('../service/user.service')
const { CDK_CODE_REQUIRED, CDK_CODE_INVALID, CDK_CODE_OUT_DATE } = require('../error/errorType')

const verifyCdk = async (ctx, next) => {
    const { code } = ctx.request.body
    if (!code || code.trim() == '') {
        return ctx.app.emit('error', new Error(CDK_CODE_REQUIRED), ctx)
    }

    // 判断cdkey是否存在且有效
    const { id: userId, name: username } = ctx.userInfo
    let [ result ] = await cdkService.getCdkByCodeAndUserId(code, userId)

    if (result) {
        if (result.status == 1) { // 说明兑换码存在但已过期
            await cdkService.remove(result.id) // 将cdkey删除
            return ctx.app.emit('error', new Error(CDK_CODE_OUT_DATE), ctx)
        } else {
            let [ { amount: oldAmount } ] = await userService.getUserInfoByName(username)
            ctx.oldAmount = Number(oldAmount)
            ctx.cdkCode = code // 说明兑换码存在且能兑换余额点
        }
    } else {
        return ctx.app.emit('error', new Error(CDK_CODE_INVALID), ctx)
    }

    await next()
}

module.exports = {
    verifyCdk
}